<!--
 * @Description: 
 * @Author: zhanyinjia
 * @Date: 2024-07-23 10:17:49
 * @LastEditors: zhanyinjia
 * @LastEditTime: 2024-07-23 13:48:32
-->
<template>
  <div>
    <img
      src="@/assets/images/file_blob_arraybuffer.png"
      alt=""
      style="width: 600px"
    >
    <hr>
    <el-select
      v-model="method"
      placeholder="读取文件的方式"
      style="width: 200px"
    >
      <el-option
        label="readAsArrayBuffer"
        value="readAsArrayBuffer"
      />
      <el-option
        label="readAsBinaryString"
        value="readAsBinaryString"
      />
      <el-option
        label="readAsDataURL"
        value="readAsDataURL"
      />
      <el-option
        label="readAsText"
        value="readAsText"
      />
    </el-select>
    <input
      type="file"
      @change="changeFiles"
    >
    <div class="result">{{ result }}</div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
export default {
  name: '',
  data() {
    return {
      method: 'readAsArrayBuffer',
      result: ''
    }
  },
  methods: {
    changeFiles(event) {
      console.log(event);
      const fileReader = new FileReader();
      fileReader[this.method](event.target.files[0]);

      // fileReader.readAsArrayBuffer(event.target.files[0]);
      // fileReader.readAsBinaryString(event.target.files[0]);
      // fileReader.readAsDataURL(event.target.files[0]);
      // fileReader.readAsText(event.target.files[0]);

      // 文件内容读取完成
      fileReader.onload = (event) => {
        try {
          this.result = event.target.result;
          console.log(this.result);

          const workbook = XLSX.read(this.result, {
            type: "binary",
          });

          // 表格是有序列表，因此可以取多个 Sheet，这里取第一个 Sheet
          const wsname = workbook.SheetNames[0];
          // 将表格内容生成 json 数据
          const sheetJson = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);

          console.log(sheetJson); // 得到的表格 JSON 内容

        } catch (e) {
          console.log(e);
          return false;
        }
      };
    }
  }
}
</script>